//
//  WeiboViewController.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-7-3.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "WeiboViewController.h"
#import "FriendsViewController.h"

@interface WeiboViewController ()


@property (nonatomic, strong) IBOutlet UIImageView *imgAttachment;
@property (nonatomic, strong) IBOutlet UILabel *sizeLabel;
@property (nonatomic, strong) IBOutlet UILabel *sbLabel;
@property (nonatomic, strong) IBOutlet UITextView *inputView;
@property (nonatomic, strong) IBOutlet UIButton *atBtn;
@property (nonatomic, strong) UIButton *rightBtn;

@property (nonatomic, strong)MBProgressHUD *HUD;

@property (nonatomic)BOOL isLogin;



@end

@implementation WeiboViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupSendButton];
    
    [self setTitle:@"分享到新浪微博"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textChanged:)
                                                 name:UITextViewTextDidChangeNotification
                                               object:self.inputView];

    
    [self.imgAttachment setImage:[UIImage imageNamed:@"cep1.jpg"]];
    
    
    
    self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:self.HUD];
	self.HUD.delegate = self;

    
    [self checkWeiboLogin];

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];

}



- (void)keyboardHide:(NSNotification *)notif {
    [self focusInput];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self focusInput];
    [self checkTextSize];
}


- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    if (![Weibo.weibo isAuthenticated]) {
        //[self checkWeiboLogin];
        self.HUD.mode = MBProgressHUDModeIndeterminate;
        
    }
    else {
        
    }
}

-(IBAction)atAction:(id)sender
{
    if (![Weibo.weibo isAuthenticated]) {
        [self checkWeiboLogin];
    }else{
        FriendsViewController *friendsController = [self.storyboard instantiateViewControllerWithIdentifier:@"friendsCtrl"];
        friendsController.delegate = self;
        [self.navigationController pushViewController:friendsController animated:YES];
        
    }
    
}

- (void)checkWeiboLogin
{
        [Weibo.weibo authorizeWithCompleted:^(WeiboAccount *account, NSError *error) {
            if (!error) {
                NSLog(@"Sign in successful: %@", account.user.screenName);
                [self.HUD hide:YES];
                [self focusInput];
            }
            else {
                NSLog(@"Failed to sign in: %@", error);
                
            }
        }];
}

- (void)passFriendName:(NSString *)value
{
    if (self.inputView.text.length + value.length +self.sbLabel.text.length < 139) {
        self.inputView.text = [NSString stringWithFormat:@"@%@ %@",value,self.inputView.text];
    }else{
        [self.HUD show:YES];
        self.HUD.labelText = @"内容长度超过限制";
        [self.HUD hide:YES afterDelay:1.8];
        self.HUD.mode = MBProgressHUDModeText;
    }
    
    NSLog(@"the get value is %@", value);
    [self checkTextSize];
}


-(void)setupSendButton{
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0, -1, 88 , 44)];
    [rightButton setTitle:@"发送" forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [rightButton addTarget:self action:@selector(send:) forControlEvents:UIControlEventTouchUpInside];
    
    self.rightBtn = rightButton;
    UIBarButtonItem* rightDrawerButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self.navigationItem setRightBarButtonItem:rightDrawerButton animated:YES];
}

- (void)send:(id)sender {
    
    if (![Weibo.weibo isAuthenticated]) {
        [self checkWeiboLogin];
    }else{
        [self postNewStatus];
        
    }
}

- (void)postNewStatus
{
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    [self.HUD show:YES];
    self.HUD.labelText = @"发送中...";
    [self.inputView resignFirstResponder];
    
    NSData *img = UIImagePNGRepresentation(self.imgAttachment.image);
    [Weibo.weibo newStatus:[NSString stringWithFormat:@"%@%@",self.inputView.text,self.sbLabel.text] pic:img completed:^(Status *status, NSError *error) {
        if (error) {
            NSLog(@"failed to upload:%@", error);
            self.HUD.mode = MBProgressHUDModeText;
            self.HUD.labelText = @"发送失败";
            [self.HUD hide:YES afterDelay:1.5];
        }
        else {
            //StatusImage *statusImage = [status.images objectAtIndex:0];
            //NSLog(@"success: %lld.%@.%@", status.statusId, status.text, statusImage.originalImageUrl);
            self.HUD.mode = MBProgressHUDModeText;
            self.HUD.labelText = @"发送成功";
            [self.HUD hide:YES afterDelay:1.5];
        }
    }];
}

- (void)focusInput {
	[self.inputView becomeFirstResponder];
}

- (void)textChanged:(NSNotification *)notification{
	self.rightBtn.enabled = self.inputView.text.length > 0;
    [self checkTextSize];
}

- (void) checkTextSize{
    self.sizeLabel.text = [NSString stringWithFormat:@"%lu/140",(unsigned long)(self.inputView.text.length + self.sbLabel.text.length)];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if (range.location>=140-self.sbLabel.text.length)
    {
        return  NO;
    }
    else
    {
        return YES;
    }
}

@end
